package com.xtrip.net.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import com.xtrip.common.BusinessConstant;
import com.xtrip.common.CtripConstant;
import com.xtrip.common.ElongConstant;
import com.xtrip.net.request.HttpRequestProperty;
import com.xtrip.util.XtripStringUtils;

public class HttpAccessAdapter {

	// 发送指定的请求到指定的URL上
	public static String SendWebserviceToUrl(String requestContent,
			String urlString, String paraName, String encode, String host,
			String soapAction,int provider) {
		ArrayList<HttpRequestProperty> StaticHttpRequestProperty = LoadStaticHttpRequestProperties(
				host, soapAction);
		InputStream errorStream = null;
		HttpURLConnection httpCon = null;
		try {
			URL url = new URL(urlString);
			String content = null;
			if(provider == BusinessConstant.PROVIDER_HOTEL_CTRIP){
				content = XtripStringUtils.XMLToString(requestContent);
			} else if(provider == BusinessConstant.PROVIDER_HOTEL_ELONG){
				content = requestContent;
			}
			String soapMessage = AddSoapShell(content,provider);;
			System.out.println(soapMessage);
			httpCon = (HttpURLConnection) url.openConnection();
			httpCon.setRequestMethod("POST");
			httpCon.setDoOutput(true);
			httpCon.setDoInput(true);

			for (int i = 0; i < StaticHttpRequestProperty.size(); i++) {
				httpCon.setRequestProperty(StaticHttpRequestProperty.get(i)
						.getName(), StaticHttpRequestProperty.get(i).getValue());
			}

			httpCon.setRequestProperty("Content-Length",
					String.valueOf(soapMessage.length()));

			OutputStream outputStream = httpCon.getOutputStream();
			outputStream.write(soapMessage.getBytes(encode));
			outputStream.close();

			InputStream inputStream = httpCon.getInputStream();
			// String encoding = httpCon.getRequestProperty("Accept-Encoding");
			BufferedReader br = null;
			// httpCon.getResponseMessage();
			if (httpCon.getRequestProperty("Accept-Encoding") != null) {
				try {
					GZIPInputStream gzipStream = new GZIPInputStream(
							inputStream);
					br = new BufferedReader(new InputStreamReader(gzipStream,
							encode));
				} catch (IOException e) {
					br = new BufferedReader(new InputStreamReader(inputStream,
							encode));
				}
			} else {
				br = new BufferedReader(new InputStreamReader(inputStream,
						encode));
			}
			StringBuffer result = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				result.append(line);
			}
			return XtripStringUtils.StringToXML(RemoveSoapShell(result.toString(),provider));

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			errorStream = httpCon.getErrorStream();
			if (errorStream != null) {
				String errorMessage = null;
				String line = null;
				BufferedReader br = new BufferedReader(new InputStreamReader(
						errorStream));
				try {
					while ((line = br.readLine()) != null) {
						errorMessage += line;
					}
					return errorMessage;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
			try {
				errorStream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpCon != null) {
				httpCon.disconnect();
			}
		}

		return "";
	}

	// sendNormal
	// 发送指定的请求到指定的URL上
	public static String SendRequestToUrl(String requestContent,
			String urlString, String paraName, String encode) {
		ArrayList<HttpRequestProperty> StaticHttpRequestPropertyN = LoadStaticHttpRequestPropertiesN();
		InputStream errorStream = null;
		HttpURLConnection httpCon = null;
		try {
			URL url = new URL(urlString);
			String content = requestContent;
			httpCon = (HttpURLConnection) url.openConnection();
			httpCon.setRequestMethod("POST");
			httpCon.setDoOutput(true);
			httpCon.setDoInput(true);

			for (int i = 0; i < StaticHttpRequestPropertyN.size(); i++) {
				httpCon.setRequestProperty(StaticHttpRequestPropertyN.get(i)
						.getName(), StaticHttpRequestPropertyN.get(i)
						.getValue());
			}

			httpCon.setRequestProperty("Content-Length",
					String.valueOf(content.length()));

			OutputStream outputStream = httpCon.getOutputStream();
			outputStream.write(content.getBytes(encode));
			outputStream.close();

			InputStream inputStream = httpCon.getInputStream();
			// String encoding = httpCon.getRequestProperty("Accept-Encoding");
			BufferedReader br = null;

			br = new BufferedReader(new InputStreamReader(inputStream, encode));
			StringBuffer result = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				result.append(line);
			}
			return result.toString();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			errorStream = httpCon.getErrorStream();
			if (errorStream != null) {
				String errorMessage = null;
				String line = null;
				BufferedReader br = new BufferedReader(new InputStreamReader(
						errorStream));
				try {
					while ((line = br.readLine()) != null) {
						errorMessage += line;
					}
					return errorMessage;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
			try {
				errorStream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpCon != null) {
				httpCon.disconnect();
			}
		}

		return "";
	}

	// 将Soap外壳添加到请求体上
		private static String AddSoapShell(String patameterValue,int provider) throws Exception {
			String template = "";
			String result = "";
			if(provider == BusinessConstant.PROVIDER_HOTEL_CTRIP){
				template = CtripConstant.CTRIP_TMP_XML;
				if(template == null)return "";
				result = template.replaceAll("string", patameterValue);
			} else if(provider == BusinessConstant.PROVIDER_HOTEL_ELONG){
				template = ElongConstant.ELONG_TMP_XML;
				if(template == null)return "";
				result = template.replaceAll("<request>string</request>", patameterValue);
			}
			return result;
		}
	// 删除Soap外壳信息
	private static String RemoveSoapShell(String source,int provider) {
		String result = "";
		if(provider == BusinessConstant.PROVIDER_HOTEL_CTRIP){
			int indexElementBegin = source.indexOf("<RequestResult>");
			int indexElementEnd = source.indexOf("</RequestResult>");
			if (indexElementBegin > 0 && indexElementEnd > 0) {
				result = source.substring(
						indexElementBegin + "<RequestResult>".length(),
						indexElementEnd);
			}
		} else if(provider == BusinessConstant.PROVIDER_HOTEL_ELONG){
			int indexElementBegin = source.indexOf("<soap:Body>");
			int indexElementEnd = source.indexOf("</soap:Body>");
			if (indexElementBegin > 0 && indexElementEnd > 0) {
				result = source.substring(
						indexElementBegin + "<soap:Body>".length(),
						indexElementEnd);
			}
		}
		
		return result;
	}
	// 加载静态信息
	private static ArrayList<HttpRequestProperty> LoadStaticHttpRequestProperties(
			String host, String soapAction) {
		ArrayList<HttpRequestProperty> staticHttpRequestProperty = new ArrayList<HttpRequestProperty>();
		staticHttpRequestProperty.add(new HttpRequestProperty("Host", host));
		staticHttpRequestProperty.add(new HttpRequestProperty("Content-Type",
				"text/xml; charset=UTF-8"));
		staticHttpRequestProperty.add(new HttpRequestProperty("SOAPAction",
				soapAction));
		staticHttpRequestProperty.add(new HttpRequestProperty(
				"Accept-Encoding", "gzip, deflate"));

		return staticHttpRequestProperty;
	}

	// 加载静态信息
	private static ArrayList<HttpRequestProperty> LoadStaticHttpRequestPropertiesN() {
		ArrayList<HttpRequestProperty> staticHttpRequestProperty = new ArrayList<HttpRequestProperty>();
//		staticHttpRequestProperty.add(new HttpRequestProperty("Host",
//				host));
		staticHttpRequestProperty.add(new HttpRequestProperty("Content-Type",
				"text/xml; charset=UTF-8"));

		return staticHttpRequestProperty;
	}

	public static void main(String[] args) {
		String request = "<Request><Header AllianceID=\"1\" SID=\"1\" TimeStamp=\"1352265056449\" Signature=\"E7C13030A4763015A3F7BA5C32613FCF\" RequestType=\"OTA_Ping\" AsyncRequest=\"false\" Timeout=\"0\" MessagePriority=\"3\"/><HotelRequest><RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ns:OTA_PingRQ><ns:EchoData>联通测试</ns:EchoData></ns:OTA_PingRQ></RequestBody></HotelRequest></Request>";
		String url = "http://openapi.ctrip.com/Hotel/OTA_Ping.asmx?wsdl";
		// String url =
		// "http://crmint.dev.sh.ctriptravel.com/Hotel/OTA_Ping.asmx?wsdl";
		String paraName = "requestXML";

		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
				paraName, "UTF-8");
		System.out.println(response);
	}

}
